﻿using Avalonia.Controls;
using Azrng.DbOperator;
using Azrng.DbOperator.Dto;
using Common.Extension;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DBCHM.Models;
using DBCHM.Service;
using DBCHM.Utils.Events;
using DBCHM.Views;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace DBCHM.ViewModels;

public partial class IndexPageViewModel : ViewModelBase
{
    private readonly IMessageService _messageService;
    private readonly IStoreService _storeService;

    public IndexPageViewModel(IMessageService messageService, IStoreService storeService)
    {
        _messageService = messageService;
        _storeService = storeService;

        TreeViewItemVms = new ObservableCollection<TreeViewItemVm>();
        ColumnInfoDtos = new ObservableCollection<ColumnInfoDto>();
        storeService.InitAsync().GetAwaiter().GetResult();
        ShowTypeEnum = typeof(ShowType);
    }

    /// <summary>
    /// 数据库类型枚举
    /// </summary>
    [ObservableProperty]
    private Type _showTypeEnum;

    /// <summary>
    /// 显示类型值
    /// </summary>
    [ObservableProperty]
    private ShowType _showTypeValue;

    /// <summary>
    /// 搜索关键字
    /// </summary>
    [ObservableProperty]
    private string? _searchKeyword;

    /// <summary>
    /// 表名
    /// </summary>
    [ObservableProperty]
    private string? _tableName;

    /// <summary>
    /// 表备注
    /// </summary>
    [ObservableProperty]
    private string? _tableRemark;

    /// <summary>
    /// 树视图展示
    /// </summary>
    public ObservableCollection<TreeViewItemVm> TreeViewItemVms { get; set; }

    /// <summary>
    /// 列信息
    /// </summary>
    public ObservableCollection<ColumnInfoDto> ColumnInfoDtos { get; set; }

    /// <summary>
    /// 打开数据连接弹框
    /// </summary>
    [RelayCommand]
    private async Task OpenConnectionDialog()
    {
        var options = new DialogOptions
                      {
                          Title = "数据库连接管理",
                          Mode = DialogMode.None,
                          Button = DialogButton.None,
                          ShowInTaskBar = false,
                          IsCloseButtonVisible = true,
                          StartupLocation = WindowStartupLocation.CenterScreen,
                          CanDragMove = true,
                          CanResize = false,
                      };
        var model = App.Current.Services.GetRequiredService<ConnectListPageViewModel>();
        await Dialog.ShowModal<ConnectListPageView, ConnectListPageViewModel>(model, options: options);
    }

    /// <summary>
    /// 数据搜索
    /// </summary>
    [RelayCommand]
    private async Task DataSearch()
    {
        await LoadData();
    }

    /// <summary>
    /// 刷新数据
    /// </summary>
    [RelayCommand]
    private void ReloadData()
    {
        _messageService.SendMessage("测试消息推送");
    }

    /// <summary>
    /// 树选中事件
    /// </summary>
    /// <param name="treeViewItemVm"></param>
    [RelayCommand]
    private async Task TreeViewSelected(TreeViewItemVm? treeViewItemVm)
    {
        if (treeViewItemVm is null || treeViewItemVm.Name.IsNullOrWhiteSpace())
            return;

        var dbConfig = await _storeService.GetCurrentConfigAsync();

        var dbBridge = DbBridgeFactory.CreateDbBridge(dbConfig.DbType, dbConfig.ConnString);

        var tableNameInfo = treeViewItemVm.Name;
        var tableArray = tableNameInfo.Split(".");

        var schemaName = tableArray.Length == 2 ? tableArray[0] : string.Empty;
        var tableName = tableArray.Length == 2 ? tableArray[1] : tableArray[0];
        var tableInfo = await dbBridge.GetTableInfoAsync(schemaName, tableName);
        if (tableInfo is null)
            return;

        TableName = tableInfo.TableName;
        TableRemark = tableInfo.TableComment;

        // 加载列信息
        var columnList = await dbBridge.GetColumnListAsync(schemaName, tableName);
        ColumnInfoDtos.Clear();
        foreach (var column in columnList.OrderBy(x => x.RowNumber))
        {
            ColumnInfoDtos.Add(column);
        }
    }

    /// <summary>
    /// 加载数据
    /// </summary>
    [RelayCommand]
    private async Task LoadData()
    {
        if (DbChmConst.CurrConnectId == 0)
        {
            _messageService.SendMessage("请先进行数据库连接");
            return;
        }

        var dbConfig = await _storeService.GetCurrentConfigAsync();

        var dbBridge = DbBridgeFactory.CreateDbBridge(dbConfig.DbType, dbConfig.ConnString);
        if (ShowTypeValue == ShowType.Table)
        {
            var schemaTable = await dbBridge.GetTableNameListAsync();

            foreach (var schema in schemaTable.GroupBy(t => t.SchemaName))
            {
                var currTree = new TreeViewItemVm(schema.Key);
                foreach (var table in schema)
                {
                    currTree.Children.Add(new TreeViewItemVm($"{schema.Key}.{table.TableName}"));
                }

                TreeViewItemVms.Add(currTree);
            }
        }
        else if (ShowTypeValue == ShowType.Proc)
        {
            var procList = await dbBridge.GetProcListAsync();
            foreach (var schema in procList.GroupBy(t => t.SchemaName))
            {
                var currTree = new TreeViewItemVm(schema.Key);
                foreach (var table in schema)
                {
                    currTree.Children.Add(new TreeViewItemVm($"{schema.Key}.{table.ProcName}"));
                }

                TreeViewItemVms.Add(currTree);
            }
        }
        else if (ShowTypeValue == ShowType.View)
        {
            // var viewList = await dbBridge.GetSchemaViewListAsync();
        }
    }
}